import 'package:casdon/common/model/tuya_category.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/modules/device/data/api/ciot_product_category_api.dart';
import 'package:casdon/modules/device/data/api/ciot_product_model_api.dart';
import 'package:casdon/modules/device/data/model/product_category_model.dart';
import 'package:casdon/modules/device/data/repository/device_repository_impl.dart';
import 'package:casdon/modules/device/domain/states/product_category_model_state.dart';
import 'package:casdon/modules/device/domain/usecase/ciot_product_category_usecase.dart';
import 'package:casdon/modules/device/domain/usecase/ciot_product_model_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final deviceRepositoryProvider = Provider(
  (ref) => DeviceRepositoryImpl(apiClient: ref.read(apiClientProvider)),
);
final ciotProductCategoryUsecaseProvider = Provider(
  (ref) => CiotProductCategoryUsecase(ref.read(deviceRepositoryProvider)),
);
final ciotProductModelUsecaseProvider = Provider(
  (ref) => CiotProductModelUsecase(ref.read(deviceRepositoryProvider)),
);

final productCategoryNotifierProvider =
    NotifierProvider<ProductCategoryNotifier, ProductCategoryModelState>(() {
      return ProductCategoryNotifier();
    });

class ProductCategoryNotifier extends Notifier<ProductCategoryModelState> {
  Future<ProductCategoryModelState> fetchData() async {
    if (state.data.isNotEmpty) {
      state = state.copyWith(isLoading: false);
      return state;
    }
    state = state.copyWith(isLoading: true);
    try {
      final ciotList = await ref
          .read(ciotProductCategoryUsecaseProvider)
          .execute();
      final tuyaList = await TuyaService().requestPrimaryCategory();
      List<ProductCategoryModel> listModel = [];
      for (ResponseCiotProductCategoryApi model in ciotList) {
        final ciotModel = ProductCategoryModel.fromCiot(model);
        listModel.add(ciotModel);
      }
      for (TuyaLevel1Category model in tuyaList) {
        final tuyaModel = ProductCategoryModel.fromTuya(model);
        final foundIndex = listModel.indexWhere(
          (item) => item.name == model.name,
        );
        if (foundIndex < listModel.length && foundIndex >= 0) {
          final copyFound = listModel[foundIndex].copyWithTuyaId(
            model.level1Code,
          );
          listModel.removeAt(foundIndex);
          listModel.insert(foundIndex, copyFound);
        } else {
          listModel.add(tuyaModel);
        }
      }
      state = state.copyWith(data: listModel, isLoading: false);
      return state;
    } on Exception catch (e) {
      Log.e("产品列表获取失败", e.toString(), StackTrace.current);
    }
    state = state.copyWith(isLoading: false);
    return state;
  }

  Future<ProductCategoryModelState> fetchProductModel(int index) async {
    if (index < 0 || index >= state.data.length) {
      state = state.copyWith(isLoading: false);
      return state;
    }

    if (state.data[index].modelList.isNotEmpty) {
      state = state.copyWith(isLoading: false);
      return state;
    }

    state = state.copyWith(isLoading: true);
    try {
      ProductCategoryModel model = state.data[index];
      final ciotId = model.ciotId;
      final tuyaId = model.tuyaId;

      var ciotList = [];
      if (ciotId != null && ciotId.isNotEmpty) {
        ciotList = await ref
            .read(ciotProductModelUsecaseProvider)
            .execute(categoryId: ciotId);
      }
      var tuyaList = [];
      if (tuyaId != null && tuyaId.isNotEmpty) {
        tuyaList = await TuyaService().requestSecondaryCategory(tuyaId, "1");
      }

      List<ProductModelModel> listModel = [];
      for (ResponseCiotProductModelApi model in ciotList) {
        final ciotModel = ProductModelModel.fromCiot(model);
        listModel.add(ciotModel);
      }

      for (TuyaLevel2Category model in tuyaList) {
        final tuyaModel = ProductModelModel.fromTuya(model);
        listModel.add(tuyaModel);
      }
      final category = state.data[index];
      category.modelList.insertAll(0, listModel);

      state.data[index] = category;

      state = state.copyWith(data: state.data, isLoading: false);
      return state;
    } on Exception catch (e) {
      Log.e("产品列表获取失败", e.toString(), StackTrace.current);
    }
    state = state.copyWith(isLoading: false);
    return state;
  }

  @override
  ProductCategoryModelState build() {
    return ProductCategoryModelState.initial();
  }
}
